//
//  HZMallSearchViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/19.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallSearchViewController.h"
#import "HZMallSearchResultViewController.h"
#import "SNWXVoiceTestViewController.h"

#import "HZImageSourceConstant.h"
//views
#import "HZTableView.h"
#import "HZSearchTextField.h"
#import "HZHotKeywordsHeaderView.h"
#import "HZDeleteHistoryKeyWordsFooterView.h"
#import "HZHistoryKeywordCell.h"
//models
#import "HZHotKeyWordsData.h"
#import "HZRemoteResult.h"
//categories
#import "UIImage+Conveniently.h"
//tools
#import "HZMallHttpManager.h"
#import "HZMallSqlDataManager.h"

//static const NSInteger kMallHomeSearchViewShortWidth = 500;
static const NSInteger kMallHomeSearchViewShortWidth = 460;
static const CGFloat kMallHomeLabelHeight = 30;
static NSString * const kMallSearchText = @" 搜索商品";

@interface HZMallSearchViewController()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, HZSearchTextFieldDelegate>

@property (strong, nonatomic) HZSearchTextField *searchTextField;
@property (strong, nonatomic) UIButton *cancelBtn;
@property (strong, nonatomic) UIButton *backBtn;
@property (strong, nonatomic) UIButton *searchBtn;
@property (strong, nonatomic) HZTableView *tableView;
@property (strong, nonatomic) HZHotKeywordsHeaderView *hotKeywordsHeaderView;
@property (strong, nonatomic) HZDeleteHistoryKeyWordsFooterView *histyFooterView;
@property (strong, nonatomic) HZHotKeyWordsData *data;
@property (strong, nonatomic) NSArray *historyArray;

@property (strong, nonatomic) HZRemoteResult *remoteData;

@end

@implementation HZMallSearchViewController

- (NSArray *)historyArray{
    if (_historyArray == nil) {
        _historyArray = [NSArray array];
    }
    return _historyArray;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = HZ_MALL_M_LIGHT_GRAY_BACKGROUND_COLOR;
    
    //关闭自动适应UIScrollView
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    //backBtn
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                            [self.ubo ow:kMallHomeLabelHeight oh:kMallHomeLabelHeight])];
    [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
    self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.backBtn addTarget:self action:@selector(cancelBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    
    //label
    self.searchTextField = [[HZSearchTextField alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                               [self.ubo uw:kMallHomeSearchViewShortWidth oh:kMallHomeLabelHeight])];
    self.searchTextField.textAlignment = NSTextAlignmentLeft;
    self.searchTextField.backgroundColor = [HZ_WHITE_COLOR colorWithAlphaComponent:1.0f];
    self.searchTextField.textColor = HZ_MALL_TEXT_M_LIGHTGRAY_COLOR;
    self.searchTextField.tintColor = HZ_MALL_TEXT_M_LIGHTGRAY_COLOR;
    self.searchTextField.delegate = self;
    self.searchTextField.searchDelegate = self;
    
    self.searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.searchTextField.layer.masksToBounds = YES;
    self.searchTextField.layer.cornerRadius = [self.ubo uw:4];
    self.searchTextField.layer.borderColor = HZ_MALL_BORDER_LINE_GRAY_COLOR.CGColor;
    self.searchTextField.layer.borderWidth = [self.ubo pw:1];
    
    self.searchTextField.placeholder = [SNUniteUrl shareUniteUrl].searchBoxText;
    self.searchTextField.font = kHZFont_Content_M;
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    
    self.navigationItem.titleView = self.searchTextField;
    
    //self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.searchTextField];
    
    /** 更改搜索样式 -wirte by khzliu */
//    //cancelBtn
//    self.cancelBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
//                                                             [self.searchTextField.ubo ow:kMallHomeLabelHeight oh:kMallHomeLabelHeight])];
//    
//    //self.cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
//    [self.cancelBtn setTitleColor:HZ_MALL_TEXT_M_LIGHTGRAY_COLOR forState:UIControlStateNormal];
//    self.cancelBtn.titleLabel.font = JKAppGlobleFontContentText;
//    [self.cancelBtn addTarget:self action:@selector(cancelBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.cancelBtn];
    
    
    //searchBtn
    self.searchBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                              [self.searchTextField.ubo ow:kMallHomeLabelHeight oh:kMallHomeLabelHeight])];
    
    self.cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [self.searchBtn setTitleColor:HZ_MALL_TEXT_M_LIGHTGRAY_COLOR forState:UIControlStateNormal];
    self.searchBtn.titleLabel.font = JKAppGlobleFontContentText;
    [self.searchBtn addTarget:self action:@selector(searchBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.searchBtn];

    
    
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf(CGPointMake(0, 0),
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT]) style:UITableViewStylePlain];
    self.tableView.backgroundColor = HZ_CLEAR_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    
    self.hotKeywordsHeaderView = [[HZHotKeywordsHeaderView alloc] initWithFrame:CGRectZero];
    self.hotKeywordsHeaderView.tabSelectedCaller = [UBTargetCaller of:self action:@selector(hotKeywordOnClick:)];
    self.tableView.tableHeaderView = self.hotKeywordsHeaderView;
    
    self.histyFooterView = [[HZDeleteHistoryKeyWordsFooterView alloc] initWithFrame:CGRectZero];
    self.histyFooterView.tabSelectedCaller = [UBTargetCaller of:self action:@selector(deleteHistoryKeywordsOnClick:)];
    
    [self.view addSubview:self.tableView];
    
    self.remoteData = [HZRemoteResult target:self action:@selector(finishLoadHotKeywords:)];
    
    //加载历史数据
    HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
    self.historyArray =[NSArray arrayWithArray:[sqlManager queryAllMallSearchHistory]];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = NO;
    
    if (self.data == nil) {
        //加载热搜词汇
        HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
        [httpManager loadHotSearchKeyWordsWithResult:self.remoteData];
    }
    
    [self refreshTableView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.searchTextField becomeFirstResponder];
}

- (void)finishLoadHotKeywords:(HZRemoteResult *)result{
    self.data = result.info;
    
    [self.hotKeywordsHeaderView showKeywords:self.data.hotKeyworsArray];

}

#pragma mark 刷新tableview
- (void)refreshTableView{
    if (self.historyArray.count == 0) {
        [self.hotKeywordsHeaderView historyTitle:NO];
        self.tableView.tableFooterView = [[UIView alloc] init];
    }else{
        [self.hotKeywordsHeaderView historyTitle:YES];
        self.tableView.tableFooterView = self.histyFooterView;
    }
    
    [self.tableView reloadData];
}


#pragma mark 点击列表显示切换
- (void)cancelBtnOnClick:(id)sender{
    [self.searchTextField resignFirstResponder];
   [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark 点击搜索按钮
- (void)searchBtnOnClick:(id)sender{
    [self.searchTextField resignFirstResponder];
    
    if (self.searchTextField.text.length) {
        NSString *keyword = self.searchTextField.text;
        
        [self showSearchResultVC:keyword saveHistory:YES];
    }else{
        if ([SNUniteUrl shareUniteUrl].searchBoxText.length) {
            NSString *keyword = [SNUniteUrl shareUniteUrl].searchBoxText;
            
            [self showSearchResultVC:keyword saveHistory:YES];
        }
    }
}

#pragma mark 点击语音搜索按钮
- (void)voiceOnClickSearchTextField{
    
    [self.searchTextField resignFirstResponder];
    SNWXVoiceTestViewController * wxVoiceVC = [[SNWXVoiceTestViewController alloc] init];
    wxVoiceVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:wxVoiceVC animated:YES];
}

#pragma mark 点击热搜词汇
- (void)hotKeywordOnClick:(NSString *)keyword{
    
    [self showSearchResultVC:keyword saveHistory:YES];
    
}

#pragma mark 删除所有搜索记录
- (void)deleteHistoryKeywordsOnClick:(UIButton *)btn{
    //保存搜索历史
    HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
    [sqlManager deleteAllSearchHistoryCacheData];
    
    self.historyArray = [NSArray array];
    
    [self refreshTableView];
}

#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.historyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZHistoryKeywordCell *cell = [HZHistoryKeywordCell cellWithTableView:(HZTableView *)tableView];
    cell.keywordLabel.text = [self.historyArray objectAtIndex:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self.ubo uh:kHistoryKeywordCellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSString *keyword = [self.historyArray objectAtIndex:indexPath.row];
    
    [self showSearchResultVC:keyword saveHistory:NO];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchTextField resignFirstResponder];
}

//点击return 按钮 去掉
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    if (textField.text.length) {
        NSString *keyword = textField.text;
        
        [self showSearchResultVC:keyword saveHistory:YES];
    }else{
        if ([SNUniteUrl shareUniteUrl].searchBoxText.length) {
            NSString *keyword = [SNUniteUrl shareUniteUrl].searchBoxText;
            
            [self showSearchResultVC:keyword saveHistory:YES];
        }
    }
    return YES;
}


#pragma mark 展示搜索结果页面
- (void)showSearchResultVC:(NSString *)keyword saveHistory:(BOOL)isNeedSave{
    if (isNeedSave) {
        //保存搜索历史
        HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
        [sqlManager updateMallSearchHistoryCacheWithData:keyword];
    }
    
    //跳转到搜索列表页面
    HZMallSearchResultViewController *mallGoodsListVC = [[HZMallSearchResultViewController alloc] init];
    mallGoodsListVC.keyword = keyword;
    [self.navigationController pushViewController:mallGoodsListVC animated:NO];
}


@end
